package com.edu.whty.common.tools;


import com.edu.whty.common.tools.redis.RedisUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//token方式请求
public class CmsOpenApiUtil {

	@Autowired
	private static RedisUtil redisUtil;
	
	/**
	 * 根据aamifUrl和平台编码，返回拼接accessToken后的用户中心访问地址
	 * @param aamifUrl 原aamif地址
	 * @param loginPlatformCode
	 * @param openSuffix  开放平台aamif接口后缀（/aamif/rest/member/query）
	 * @return
	 */
	public static String getTokenUrl(String aamifUrl,String openSuffix,String loginPlatformCode,String netIp){
		String cmsOpenApi = SysConfig.getStrValue("cmsOpenApi",loginPlatformCode,loginPlatformCode);
		String open_url = SysConfig.getStrValue("open_url",loginPlatformCode,loginPlatformCode);
		String appid = SysConfig.getStrValue("jxzsAppId",loginPlatformCode,loginPlatformCode);
		String appkey = SysConfig.getStrValue("jxzsAppKey",loginPlatformCode,loginPlatformCode);
		if(null != cmsOpenApi && "open".equals(cmsOpenApi)){
			aamifUrl = open_url + openSuffix;
			if(aamifUrl.contains("?")){
				aamifUrl+="&accessToken="+getAccessToken(open_url,appid,appkey,loginPlatformCode,netIp);
			}else{
				aamifUrl+="?accessToken="+getAccessToken(open_url,appid,appkey,loginPlatformCode,netIp);
			}
		}
		
		return aamifUrl;
	}
	
	
	public static String getTokenUrl(String aamifUrl,String openSuffix,String loginPlatformCode,String netIp,String platformCode){
		String cmsOpenApi = SysConfig.getStrValue("cmsOpenApi",loginPlatformCode,platformCode);
		String open_url = SysConfig.getStrValue("open_url",loginPlatformCode,loginPlatformCode);
		String appid = SysConfig.getStrValue("jxzsAppId",loginPlatformCode,loginPlatformCode);
		String appkey = SysConfig.getStrValue("jxzsAppKey",loginPlatformCode,loginPlatformCode);
		if(null != cmsOpenApi && "open".equals(cmsOpenApi)){
			aamifUrl = open_url + openSuffix;
			if(aamifUrl.contains("?")){
				aamifUrl+="&accessToken="+getAccessToken(open_url,appid,appkey,loginPlatformCode,netIp);
			}else{
				aamifUrl+="?accessToken="+getAccessToken(open_url,appid,appkey,loginPlatformCode,netIp);
			}
		}
		
		return aamifUrl;
	}
	
	/*
	 * 获取开放平台accessToken   慧教云
	 */
	public static String getAccessToken(String open_url,String appid,String appkey,
			String loginPlatformCode,String netIp) {
		if(loginPlatformCode==null){
			HttpServletRequest request = null;
			try {
				request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			} catch (Exception e) {
				System.out.println("getAccessToken---获取request对象异常");;
			}
			loginPlatformCode = (String)request.getSession().getAttribute("loginPlatformCode");
		}
		String accessToken = null;
		try {
			accessToken = redisUtil.get("cache_getAccessToken_"+loginPlatformCode).toString();
			if(StringUtils.isEmpty(accessToken)){
				/****慧教云开放平台appid、appkey、网关接口域名、平台码****/
				String openapigatewayUrl = open_url+"/apigateway/getAccessToken";
				//long timeMills = System.currentTimeMillis() + 2592000000L;
				long timeMills = System.currentTimeMillis();
				String ts = (new StringBuilder(String.valueOf(timeMills))).toString();
				String keyinfo = (new StringBuilder(String.valueOf(appid))).append(appkey).append(ts).toString();
				byte hmacSHA[] = EncryptionUtils.getHmacSHA1(keyinfo, appkey);
				String digest = EncryptionUtils.bytesToHexString(hmacSHA);
				digest = digest.toUpperCase();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("appid", appid);
				jsonObject.put("timestamp", ts);
				jsonObject.put("keyinfo", digest);
				//jsonObject.put("platformCode", loginPlatformCode);
				String accessTokenResult =  HttpClientUtil.post(openapigatewayUrl, jsonObject.toString(),netIp);
				if(StringUtils.isNotEmpty(accessTokenResult)){
					JSONObject accessTokenResultJson = JSONObject.fromObject(accessTokenResult);
					if("000000".equals(accessTokenResultJson.getString("retCode")) ){
						accessToken = accessTokenResultJson.getJSONObject("tokenInfo").getString("accessToken");
						redisUtil.set("cache_getAccessToken_"+loginPlatformCode, accessToken, 29*60);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return accessToken;
	}
	
}
